/* global $ */
// 从 LocalStorage 获取 userInfo
// 检查登录状态
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
const userInfoString = isLoggedIn ? JSON.parse(localStorage.getItem('userInfo')) : null;
let userId;
if (userInfoString) {
    // 获取userId
    userId = userInfoString.userId;
    console.log('从LocalStorage获取的用户ID:', userId);
} else {
    console.log("未拿到userId")
}

// function signalert(alert, color) {
//     if (alert) {
//         alert.style.display = 'block';
//         // alert.innerHTML = message;
//         alert.style.color = color;
//         setTimeout(function () {
//             alert.style.display = 'none';
//         }, 2000); //两秒后警告框消失
//     }
// }
function otherUserPage(otherUserId) {
    if (isLoggedIn) {
        location.href = `/redirectToPage/${otherUserId}`;
    } else {
        showAlert("请先登录", 'red');

    }
}
document.addEventListener('DOMContentLoaded', function () {
    const userAvatars = document.querySelectorAll('.userAvatar');
    userAvatars.forEach((userAvatar) => {
        userAvatar.addEventListener('click', () => {
            const avatarId = userAvatar.dataset.userId;
            otherUserPage(avatarId);
        })
    })
});

const alert = document.querySelector('.alert');
function showAlert(message, color) {
    alert.textContent = message;
    alert.style.color = color;
    alert.style.display = 'block';
    setTimeout(() => {
        alert.style.display = 'none';
    }, 3000);
}
const loginPleaseButton = document.querySelector('.login-please-button');
const postEssay = document.querySelector('.post-Essay');

if (loginPleaseButton) {
    loginPleaseButton.addEventListener('click', function () {
        console.log("11");
        location.href = "/user/login";
    });
}
if (postEssay) {
    postEssay.addEventListener('click', function (event) {
        if (isLoggedIn) {
            location.href = "/NewsController/toPost";
        } else {
            showAlert("请先登录", 'red');
        }
    })
}
// 封装通用跳转函数
function bindClickToPersonalPage(selectors, url) {
    const elements = typeof selectors === 'string'
        ? document.querySelectorAll(selectors)
        : selectors;
    //过滤掉不存在的元素
    const validElements = Array.from(elements).filter(el => el);

    validElements.forEach(element => {
        element.addEventListener('click', (event) => {
            event.preventDefault();
            console.log(`触发跳转：${element.className || element.id}`);
            location.href = url;
        });
    });
}

const likesReceived = document.querySelector('.likes-received');
const fans = document.querySelector('.fans');
const follows = document.querySelector('.follows');
bindClickToPersonalPage('.img-id', '/user/personal_page');
bindClickToPersonalPage([likesReceived, fans, follows], '/user/personal_page');
//更换导航条
const topNav = document.querySelector('.top-bar-first');
const fixedNav = document.querySelector('.top-bar-second');

window.addEventListener('scroll', function () {
    const scrollTop = document.documentElement.scrollTop;
    if (scrollTop < 400) {
        topNav.style.position = 'fixed';
        fixedNav.style.top = '-64px'; /* 滚动超过顶部导航条高度，让固定导航条滑入 */
    } else {
        topNav.style.position = 'static';
        fixedNav.style.top = '0px';/*滑动超出474px,就让第二个导航条滑出*/

    }
});
function goToEssayPage(postId, userId) {
    //将当前文章的postId和作者id存储起来
    localStorage.setItem('currentPostId', postId);
    localStorage.setItem('authorId', userId);

    window.location.href = `/NewsController/${postId}`;
}

document.addEventListener('DOMContentLoaded', function () {
    const newsContents = document.querySelectorAll('.news-contents');
    console.log(newsContents);
    newsContents.forEach(newsContent => {
        newsContent.addEventListener('click', () => {
            console.log("一点击");
            const newsPostId = newsContent.querySelector('.news-postId');
            const newsUserId = newsContent.querySelector('.news-userId');
            if (newsPostId && newsUserId) {
                console.log(newsPostId.textContent);
                console.log(newsUserId.textContent);
                goToEssayPage(newsPostId.textContent, newsUserId.textContent);
            } else {
                console.error('未找到对应的 postId 或 userId 元素');
            }
        });
    });
    //对搜索出来的用户进行关注
    const userContents = document.querySelectorAll('.user-contents');
    userContents.forEach(userContent => {
        const newsUserId = userContent.querySelector('.news-userId');
        const followBtn = userContent.querySelector('.followBtn');
        followBtn.addEventListener('click', () => {
            $.ajax({
                url: '/NewsController/follow',
                type: "post",
                data: { followedId: newsUserId.textContent },
                success: function (result) {
                    console.log(result);
                    if (result.message == "成功关注") {
                        followBtn.style.backgroundColor = '#F9F9F9';
                        followBtn.style.color = '#999999';
                        followBtn.innerHTML = "已关注";
                    }
                    if (result.message == "取消关注") {
                        followBtn.style.backgroundColor = 'red';
                        followBtn.style.color = 'white';
                        followBtn.innerHTML = "关注";
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            })
        })
    })


});
function goToCategory(categoryId) {
    sessionStorage.setItem('currentCategoryId', categoryId);
    window.location.href = `/category/${categoryId}`;
}

const categoryItems = document.querySelectorAll('.main-categories li');
categoryItems.forEach(function (item) {
    item.addEventListener('click', function () {
        console.log(this.id);
        const categoryId = this.id;

        goToCategory(categoryId);
    });
});
//分类页面内容更改
const item=document.querySelector('.item');
// const followsContent=document.querySelector('.follows-content');
// if(followsContent){
//     $.ajax({
//        url:"/user/selectFollowerPost",
//         type:"GET",
//         data:{
//            pageSize:10,
//             start:1,
//         },
//         success:function(result){
//            console.log(result.data);
//             let html='';
//            const newPosts=result.data.posts;
//             newPosts.forEach(function(post){
//                 console.log(post);
//                 html+=createPostsHtml(post);
//             })
//             item.innerHTML=html;
//         },
//         error:function(error){
//            console.log(error);
//         }
//     })
// }
const recommendElement = document.querySelector('.recommend');
if (recommendElement) {
    recommendElement.classList.add('active');

}
const storedCategoryId = sessionStorage.getItem('currentCategoryId');
if (storedCategoryId) {
    console.log(storedCategoryId);
    const categoryItems = document.querySelectorAll('.main-categories li');
    categoryItems.forEach(function (item) {
        // console.log(item.id );
        if (item.id === storedCategoryId) {
            recommendElement.classList.remove('active');

            item.classList.add('active');
        }
    });
}

//首页内容的无限滚动
let currentPostsPage = 1;
let isLoading = false; // 新增：加载状态标志
let shouldShowMoreButton = true;
let categoryId;
// 监听滚动事件等触发加载更多的逻辑
$(window).scroll(function () {
    // 当满足加载条件时
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200 && !isLoading && shouldShowMoreButton) {
        loadMorePosts(currentPostsPage + 1);

    }
});
function loadMorePosts(pageNum) {
    //设置加载状态
    isLoading = true;
    // 显示加载提示
    showLoadingIndicator();
    setTimeout(() => {
        const category = document.querySelector('.main-categories li.active');
        if (category) {
            categoryId = category.id;
            // 构建请求URL
            const url = `/category/findPost/${categoryId}`;
            $.ajax({
                url: url,
                method: 'GET',
                data: {
                    categoryId: categoryId,
                    pageNum: pageNum
                },
                success: function (response) {
                    // 移除加载提示
                    removeLoadingIndicator();

                    console.log("请求成功")
                    console.log(response);
                    // const MorePosts=document.querySelector('#more-posts');
                    // if(MorePosts){
                    //     console.log("获取到显示更多文章的按钮");
                    //     MorePosts.remove();
                    // }
                    const newPosts = response.data.posts;
                    console.log(`加载第${pageNum}页，共${newPosts.length}条文章`);
                    console.log(newPosts);
                    let html = '';
                    newPosts.forEach(function (post) {
                        console.log(post)
                        html += createPostsHtml(post);
                    })
                    item.insertAdjacentHTML('beforeend', html);
                    // 更新状态
                    currentPostsPage = pageNum;
                    shouldShowMoreButton = response.data.hasMore;
                    // const title=document.querySelectorAll('.title');
                    truncateTitles({ selector: '.title', maxLength: 30 });
                    // 如果没有更多内容，显示提示
                    if (!shouldShowMoreButton) {
                        showNoMoreContent();
                    }
                },
                error: function () {
                    console.log('请求失败');
                },
                complete: function () {
                    // 请求完成后重置加载状态
                    isLoading = false;
                }

            });
        }

    }, 1000);

}
// 显示加载提示
function showLoadingIndicator() {
    const loadingIndicator = document.createElement('div');
    loadingIndicator.id = 'loading-indicator';
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.textContent = '正在加载更多内容...';
    $('.item').append(loadingIndicator);
}

// 移除加载提示
function removeLoadingIndicator() {
    const loadingIndicator = document.getElementById('loading-indicator');
    if (loadingIndicator) {
        loadingIndicator.remove();
    }
}
// 显示没有更多内容提示
function showNoMoreContent() {
    const noMorePosts = document.createElement('div');
    noMorePosts.id = 'no-more-posts';
    noMorePosts.className = 'no-more-posts';
    noMorePosts.textContent = '暂无更多内容';
    $('.item').append(noMorePosts);
}

// 显示加载错误提示
function showLoadError() {
    const errorIndicator = document.createElement('div');
    errorIndicator.id = 'load-error';
    errorIndicator.className = 'load-error';
    errorIndicator.textContent = '加载失败，请重试';
    $('.item').append(errorIndicator);

    // 3秒后自动移除错误提示
    setTimeout(() => {
        const error = document.getElementById('load-error');
        if (error) {
            error.remove();
        }
    }, 3000);
}
// 标题截断函数
function truncateTitles({ selector, maxLength = 30, ellipsis = '.....' }) {
    const elements = document.querySelectorAll(selector);
    elements.forEach(element => {
        if (element.textContent.length > maxLength) {
            element.textContent = element.textContent.slice(0, maxLength) + ellipsis;
        }
    });
}
const title = document.querySelectorAll('.title');
truncateTitles({ selector: '.title' });
const hotTitle = document.querySelectorAll('.hot-content');
truncateTitles(30, hotTitle);
// 创建评论 HTML 模板函数
function createPostsHtml(post) {
    return `
    <div class="news-contents" onclick="goToEssayPage('${post.postId}', '${post.userId}')">
                    <div class="feed-card" >
                        <span class="news-postId" style="display:none">${post.postId}</span>
                        <span class="news-userId"  style="display:none">${post.userId}</span>
                        <a class="title">${post.title}</a>
                        <div class="feed-card-bottom">
                            <span class="comments-num"><span>${post.commentCount}</span>评论</span>
                            <span class="post-date">${post.createdTime}</span>
                        </div>
                    </div>
                    <div class="news-image">
                        <a>
                            <img src="${post.coverImage}" alt="">
                        </a>
                    </div>
                </div>
    `;
}
//添加"显示更多文章"按钮
function addMorePostsButton() {
    console.log(shouldShowMoreButton);
    if (!shouldShowMoreButton) {
        return;
    } else {
        console.log("要显示按钮了");
        const morePosts = document.createElement('div');
        morePosts.id = 'more-posts';
        morePosts.textContent = "正在获取更多内容";
        item.appendChild(morePosts);
    }
}

// 搜索功能
const searchInput = document.querySelector('.search-input');
const searchButton = document.querySelector('.icon-search');
console.log(searchButton);

//显示当前用户的总获赞数
function allLike(userId) {
    const likesCount = document.querySelector('.likesCount');
    if (likesCount) {
        $.ajax({
            url: `/NewsController/allLike/${userId}`,
            type: "GET",
            data: { userId: userId },
            success: function (result) {
                console.log(result);
                likesCount.textContent = result;
            },
            error: function (error) {
                console.log("获取总点赞数失败", error);
            }

        })
    }

}
allLike(userId);
//显示当前用户的总粉丝数
function countfollowed(userId) {
    const fansCount = document.querySelector('.fansCount');
    if (fansCount) {
        $.ajax({
            url: "/NewsController/countfollowed",
            type: "GET",
            data: { userId: userId },
            success: function (result) {
                console.log(result);
                fansCount.textContent = result.data;
            },
            error: function (error) {
                console.log("获取总点赞数失败", error);
            }

        })
    }

}
countfollowed(userId);
//显示当前用户的总关注数
function countfollower(userId) {
    const followsCount = document.querySelector('.followsCount');
    if (followsCount) {
        $.ajax({
            url: "/NewsController/countfollower",
            type: "GET",
            data: { userId: userId },
            success: function (result) {
                console.log(result);
                followsCount.textCount = result.data;
            },
            error: function (error) {
                console.log("获取总点赞数失败", error);
            }

        })
    }

}
countfollower(userId);

//全部热搜
let currentPage = 1; // 当前页码，初始为第1页（显示1-10条）

// 页面加载时初始化热搜
loadHotSearch(currentPage);

// 加载热搜数据
function loadHotSearch(pageNum) {
    $.ajax({
        url: `/SearchController/HotSearch/${pageNum}`, // 假设接口路径为/hotSearchJson
        type: "GET",
        data: { Num: pageNum }, // 传递页码参数
        success: function (response) {
            console.log(response);
            if (response.message.includes("成功")) {
                renderHotSearch(response);
                currentPage = pageNum; // 更新当前页码
                // console.log(righthotContent.innerHTML);
            } else if (response.message === '热搜列表为空！') {
                if (pageNum > 1) {
                    // alert("没有更多热搜数据，返回前十条");
                    currentPage = 1;
                    loadHotSearch(currentPage);
                    return;
                } else {
                    // alert("暂无热搜数据");
                    return;
                }
            }

        },
        error: function (error) {
            // alert("获取热搜失败，请重试！");
            console.log(error);
        }
    });
}

// 渲染热搜列表
function renderHotSearch(response) {
    const righthotContent = document.querySelector('.right-hot-content');
    console.log(righthotContent);
    if (!righthotContent) {
        console.error('未找到类名为 hot-content 的元素');
        return;
    }
    righthotContent.innerHTML = '';
    let htmlStr = '';
    const keywords = response.keywords;
    const postLists = response.postLists;
    for (let i = 0; i < keywords.length; i++) {
        const keyword = keywords[i];
        const postId = postLists[i].postId;
        const userId = postLists[i].userId;
        const rank = currentPage === 1 ? i + 1 : (currentPage - 1) * 10 + i + 1;
        htmlStr += `
            <li onclick="goToEssayPage('${postId}', '${userId}')">
                <span class="heat-rank">
                    ${rank}
                </span>
                <span class="heat-text">${keyword}</span>
            </li>
        `;
    }
    righthotContent.innerHTML = htmlStr;
    truncateTitles({ selector: '.heat-text', maxLength: 12 });
}

// 切换页码（换一换）
function loadNextHotSearch() {
    currentPage++; // 页码递增
    loadHotSearch(currentPage);
}

// 重置为前十条
function resetHotSearch() {
    currentPage = 1;
    loadHotSearch(currentPage);
}
